package cn.iocoder.yudao.module.crossborder.platform.controller.webhook.amazon;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon.AmazonWebhookProvider;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "Amazon Webhook - 回调接口")
@RestController
@RequestMapping("/crossborder/webhook/amazon")
@Validated
@Slf4j
public class AmazonWebhookController {

    @Resource
    private AmazonWebhookProvider amazonWebhookProvider;

    @PostMapping("/notifications")
    @Operation(summary = "接收Amazon通知", description = "接收Amazon平台的Webhook通知")
    public CommonResult<Boolean> receiveNotifications(@RequestBody String payload,
                                                      HttpServletRequest request) {
        log.info("接收到Amazon Webhook通知: {}", payload);
        
        // 获取请求头信息
        Map<String, String> headers = getHeaders(request);
        
        // 处理Webhook事件
        boolean result = amazonWebhookProvider.handleWebhookEvent(payload, headers);
        
        return success(result);
    }

    @PostMapping("/subscription-confirmation")
    @Operation(summary = "确认Amazon订阅", description = "确认Amazon SNS订阅")
    public CommonResult<Boolean> confirmSubscription(@RequestBody String payload,
                                                     HttpServletRequest request) {
        log.info("接收到Amazon订阅确认: {}", payload);
        
        // 获取请求头信息
        Map<String, String> headers = getHeaders(request);
        
        // 处理订阅确认
        boolean result = amazonWebhookProvider.handleSubscriptionConfirmation(payload, headers);
        
        return success(result);
    }

    /**
     * 获取请求头信息
     */
    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> headers = new java.util.HashMap<>();
        java.util.Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.put(headerName, request.getHeader(headerName));
        }
        return headers;
    }

}
